package com.pangolin.pangolinim.ui.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.StrictMode;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.lqr.emoji.EmotionKeyboard;
import com.lqr.emoji.EmotionLayout;
import com.lqr.emoji.IEmotionExtClickListener;
import com.lqr.emoji.IEmotionSelectedListener;
import com.luck.picture.lib.PictureSelector;
import com.lqr.recyclerview.LQRRecyclerView;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.language.LanguageConfig;
import com.orhanobut.logger.Logger;
import com.pangolin.pangolinim.R;
import com.pangolin.pangolinim.app.BroadcastMsg;
import com.pangolin.pangolinim.service.list.MessageList;
import com.pangolin.pangolinim.sqlite.DBMessage;
import com.pangolin.pangolinim.ui.adapter.SessionAdapter;
import com.pangolin.pangolinim.ui.adapter.UIContact;
import com.pangolin.pangolinim.ui.adapter.UIMessage;
import com.pangolin.pangolinim.ui.base.BaseActivity;
import com.pangolin.pangolinim.utils.BundleUtil;
import com.pangolin.pangolinim.utils.FileUtil;
import com.pangolin.pangolinim.utils.GlideEngine;
import com.pangolin.pangolinim.utils.GsonUtil;
import com.pangolin.pangolinim.utils.ImageUtil;
import com.pangolin.pangolinim.utils.MD5Util;
import com.pangolin.pangolinim.utils.UIUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.bingoogolapple.refreshlayout.BGANormalRefreshViewHolder;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;


public class SessionActivity extends BaseActivity implements IEmotionSelectedListener, BGARefreshLayout.BGARefreshLayoutDelegate {
    private int msgPosition = 0;        //当前消息的位置
    private final int msgLimit = 20;    //一次读取消息数量
    public UIContact me;               //自己的用户信息
    public UIContact contact;          //对方用户信息
    private boolean isFirstRun = true;  //是否是首次打开

    private SessionAdapter mAdapter;
    public static List<UIMessage> mMessages =  new ArrayList<UIMessage>();

    private ImageButton mIbToolbarMore;
    private EmotionLayout mElEmotion;
    private EditText mEtContent;
    private LinearLayout mLlContent;
    private FrameLayout mFlEmotionView;
    private ImageView mIvEmo;
    private ImageView mIvMore;
    private LQRRecyclerView mRvMsg;
    private LinearLayout mLlMore;
    private Button mBtnSend;
    private RelativeLayout mRlAlbum;
    private RelativeLayout mRlTakePhoto;
    private BGARefreshLayout mRefreshLayout;

    private EmotionKeyboard mEmotionKeyboard;


    @Override
    protected void init(){
        String strMe = getIntent().getStringExtra("param1");
        String strContact = getIntent().getStringExtra("param2");
        if(strContact != null && strMe != null){
            contact = GsonUtil.fromJson(strContact , UIContact.class);
            me = GsonUtil.fromJson(strMe , UIContact.class);
            Logger.d("me:%d|%s\ncontact:%d|%s" ,me.getUid() , me.getName() , contact.getUid() , contact.getName());
        }
        initPhotoError();
    }

    @Override
    protected void initView(){
        mIbToolbarMore = findViewById(R.id.ibToolbarMore);
        mElEmotion = findViewById(R.id.elEmotion);
        mEtContent = findViewById(R.id.etContent);
        mLlContent = findViewById(R.id.llContent);
        mFlEmotionView = findViewById(R.id.flEmotionView);
        mIvEmo = findViewById(R.id.ivEmo);
        mIvMore = findViewById(R.id.ivMore);
        mRvMsg = findViewById(R.id.rvMsg);
        mLlMore = findViewById(R.id.llMore);
        mBtnSend = findViewById(R.id.btnSend);
        mRlAlbum = findViewById(R.id.rlAlbum);
        mRlTakePhoto = findViewById(R.id.rlTakePhoto);
        mRefreshLayout = findViewById(R.id.refreshLayout);

        mIbToolbarMore.setImageResource(R.mipmap.ic_session_info);
        mIbToolbarMore.setVisibility(View.VISIBLE);
        mElEmotion.attachEditText(mEtContent);
        initEmotionKeyboard();
        initRefreshLayout();

        if(contact != null){
            setToolbarTitle(String.valueOf(contact.getUid()));
        }else{
            setToolbarTitle("");
        }

        setAdapter();
    }

    @Override
    protected void initListener(){
        mIbToolbarMore.setOnClickListener(v -> {
            jumpToActivity(SessionInfoActivity.class ,GsonUtil.toJson(me) , GsonUtil.toJson(contact));
        });
        mElEmotion.setEmotionSelectedListener(this);
        mElEmotion.setEmotionAddVisiable(true);
        mElEmotion.setEmotionSettingVisiable(true);
        mElEmotion.setEmotionExtClickListener(new IEmotionExtClickListener() {
            @Override
            public void onEmotionAddClick(View view) {
                UIUtil.showToast("add");
            }

            @Override
            public void onEmotionSettingClick(View view) {
                UIUtil.showToast("setting");
            }
        });
        mLlContent.setOnTouchListener((v, event) -> {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    closeBottomAndKeyboard();
                    break;
            }
            return false;
        });
        mRvMsg.setOnTouchListener((v, event) -> {
            closeBottomAndKeyboard();
            return false;
        });

        mEtContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (mEtContent.getText().toString().trim().length() > 0) {
                    mBtnSend.setVisibility(View.VISIBLE);
                    mIvMore.setVisibility(View.GONE);
                } else {
                    mBtnSend.setVisibility(View.GONE);
                    mIvMore.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mEtContent.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                //滚动到底部
                mRvMsg.scrollToPosition(mMessages.size() - 1);
            }
        });
        mBtnSend.setOnClickListener(v -> {
            //发送按钮
            UIMessage message = new UIMessage();
            message.setMid(MD5Util.encrypt(mEtContent.getText().toString()));
            message.setUid(contact.getUid());
            message.setMsgtext(mEtContent.getText().toString());
            message.setType(UIMessage.MSG_TEXT);
            message.setStatus(1);
            message.setIo(UIMessage.MSG_SEND);
            sendMessage(message);
            mEtContent.setText("");
        });
        mRlAlbum.setOnClickListener(v -> {
            //获取用户选择的图片路径
            picPicker();
        });
        mRlTakePhoto.setOnClickListener(v -> {
            //起调相机
            photoPicker();
        });
    }

    /**
     TODO：调用系统图片选择器
     */
    private void picPicker(){
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .imageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_WeChat_style)
                .isWeChatStyle(true)
                .imageSpanCount(3)// 每行显示个数
                .selectionMode(PictureConfig.MULTIPLE )// 多选 or 单选
                .isCamera(false)// 是否显示拍照按钮
                .isGif(false)// 是否显示gif图片
                .setLanguage(LanguageConfig.CHINESE)    //中文版
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }

    /**
     TODO：调用系统相机
     */
    private void photoPicker(){
        PictureSelector.create(this)
                .openCamera(PictureMimeType.ofImage())
                .imageEngine(GlideEngine.createGlideEngine())
                .setLanguage(LanguageConfig.CHINESE)    //中文版
                .forResult(PictureConfig.REQUEST_CAMERA);//结果回调onActivityResult code
    }

    @Override
    protected void onResume() {
        super.onResume();
        //设置后台服务状态
        Map<String, Object> brocastMap = new HashMap<String, Object>();
        brocastMap.put("type" , BroadcastMsg.DATA_UI_SETCONFIG);
        brocastMap.put("key" , "sessionuid");
        brocastMap.put("value" , contact.getUid());
        BundleUtil bundleUtilSend = new BundleUtil(BroadcastMsg.SIG_UI_DATA , brocastMap , null);
        BroadcastSender(bundleUtilSend.getBundle());
        //首次运行拉取一次聊天记录
        if(isFirstRun){
            mMessages.clear();
            mAdapter.notifyDataSetChanged();
            //拉取最近20条聊天记录
            getMessage(contact.getUid() , msgPosition , msgLimit);
            isFirstRun = false;
        }
    }

    @Override
    protected void onPause(){
        super.onPause();
        //设置后台服务状态
        Map<String, Object> brocastMap = new HashMap<String, Object>();
        brocastMap.put("type" , BroadcastMsg.DATA_UI_SETCONFIG);
        brocastMap.put("key" , "sessionuid");
        brocastMap.put("value" , 0);
        BundleUtil bundleUtilSend = new BundleUtil(BroadcastMsg.SIG_UI_DATA , brocastMap , null);
        BroadcastSender(bundleUtilSend.getBundle());
    }

    @Override
    protected void CoreMessage(BundleUtil bundleUtil){
        if(bundleUtil.getType() == BroadcastMsg.SIG_CORE_DATA){
            if(bundleUtil.getData() != null){
                Map<String, Object> resMap = bundleUtil.getData();
                Logger.d(resMap);
                if((int) resMap.get("type") == BroadcastMsg.DATA_CORE_GETMSG){
                    if((int)resMap.get("result") == 0){
                        String str_messages = (String) resMap.get("messages");
                        if(str_messages != null){
                            MessageList messageList = GsonUtil.fromJson(str_messages , MessageList.class);
                            if (messageList != null){
                                loadMessages(messageList.get_allmessages());
                            }
                        }
                    }else{
                        UIUtil.showToast((String) resMap.get("msg"));
                    }
                }else if((int) resMap.get("type") == BroadcastMsg.DATA_CORE_DOWNPIC){
                    if((int)resMap.get("result") == 0){
                        reloadPic();
                    }else{
                        UIUtil.showToast((String) resMap.get("msg"));
                    }
                }else if((int) resMap.get("type") == BroadcastMsg.DATA_CORE_UPLOADPIC){
                    if((int) resMap.get("result") == 0){
                        //发送图片类型消息
                        UIMessage message = new UIMessage();
                        message.setMid(MD5Util.encrypt((String) resMap.get("filename")));
                        message.setUid(contact.getUid());
                        message.setMsgtext((String) resMap.get("filename"));
                        message.setType(UIMessage.MSG_IMG);
                        message.setStatus(1);
                        message.setIo(UIMessage.MSG_SEND);
                        sendMessage(message);
                    }
                }else if((int) resMap.get("type") == BroadcastMsg.DATA_CORE_CLIMSG){
                    if((int) resMap.get("uid") == contact.getUid()){
                        UIMessage message = new UIMessage();
                        message.setIo(UIMessage.MSG_RECV);
                        message.setUid((int) resMap.get("uid"));
                        message.setMsgtext((String) resMap.get("context"));
                        message.setType((int) resMap.get("msgtype"));
                        message.setTimestamp((int) resMap.get("time"));
                        message.setMid((String) resMap.get("mid"));
                        if(message.getType() == UIMessage.MSG_IMG){
                            File file = new File(getExternalFilesDir(String.valueOf(me.getUid())) , message.getMsgtext());
                            if(file.exists() && file.isFile()){
                                DisplayMetrics dm = getResources().getDisplayMetrics();
                                int width = dm.widthPixels / 3;     //宽度不超过屏幕1/3
                                int height = dm.heightPixels / 2;       //高度不超过屏幕1/2
                                message.setBitmap(ImageUtil.getBitmapFromFile(this , file , width , height));
                            }else{
                                //通知服务下载头像图片
                                Map<String, Object> brocastMap = new HashMap<String, Object>();
                                brocastMap.put("type" , BroadcastMsg.DATA_UI_DOWNPIC);
                                brocastMap.put("uid" , contact.getUid());
                                brocastMap.put("filename" , message.getMsgtext());
                                BundleUtil bundleUtilSend = new BundleUtil(BroadcastMsg.SIG_UI_DATA , brocastMap , null);
                                BroadcastSender(bundleUtilSend.getBundle());
                            }
                        }
                        mMessages.add(message);
                        mAdapter.notifyDataSetChanged();
                        //滚动到底部
                        mRvMsg.scrollToPosition(mMessages.size() - 1);
                        //session界面下要通知后台消息已读
                        Map<String, Object> brocastMap = new HashMap<String, Object>();
                        brocastMap.put("type" , BroadcastMsg.DATA_UI_SETSESSION);
                        brocastMap.put("uid" , contact.getUid());
                        brocastMap.put("unread" , 0);
                        BundleUtil bundleUtilSend = new BundleUtil(BroadcastMsg.SIG_UI_DATA , brocastMap , null);
                        BroadcastSender(bundleUtilSend.getBundle());
                    }
                }
            }
        }
    }

    @Override
    protected int provideContentViewId(){
        return R.layout.activity_session;
    }

    private void  initEmotionKeyboard() {
        mEmotionKeyboard = EmotionKeyboard.with(this);
        mEmotionKeyboard.bindToEditText(mEtContent);
        mEmotionKeyboard.bindToContent(mLlContent);
        mEmotionKeyboard.setEmotionLayout(mFlEmotionView);
        mEmotionKeyboard.bindToEmotionButton(mIvEmo, mIvMore);
        mEmotionKeyboard.setOnEmotionButtonOnClickListener(view -> {
            switch (view.getId()) {
                case R.id.ivEmo:
//                    UIUtil.postTaskDelay(() -> mRvMsg.smoothMoveToPosition(mRvMsg.getAdapter().getItemCount() - 1), 50);
                    mEtContent.clearFocus();
                    if (!mElEmotion.isShown()) {
                        if (mLlMore.isShown()) {
                            showEmotionLayout();
                            hideMoreLayout();
                            return true;
                        }
                    } else if (mElEmotion.isShown() && !mLlMore.isShown()) {
                        mIvEmo.setImageResource(R.mipmap.ic_cheat_emo);
                        return false;
                    }
                    showEmotionLayout();
                    hideMoreLayout();
                    break;
                case R.id.ivMore:
//                    UIUtil.postTaskDelay(() -> mRvMsg.smoothMoveToPosition(mRvMsg.getAdapter().getItemCount() - 1), 50);
                    mEtContent.clearFocus();
                    if (!mLlMore.isShown()) {
                        if (mElEmotion.isShown()) {
                            showMoreLayout();
                            hideEmotionLayout();
                            return true;
                        }
                    }
                    showMoreLayout();
                    hideEmotionLayout();
                    break;
            }
            return false;
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            List<LocalMedia> results = PictureSelector.obtainMultipleResult(data);
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    for (LocalMedia result : results){
                        //Logger.d("select Gallery pic: %s:%d:%d" , result.getFileName() , result.getHeight() , result.getWidth());
                        try {
                            //拷贝到程序私有目录
                            String newFile = FileUtil.copyGalleryToPrivate(
                                    UIUtil.getContext() ,
                                    Uri.parse(result.getPath()) ,
                                    String.valueOf(me.getUid()),
                                    result.getHeight() ,
                                    result.getWidth());
                            Logger.d("onActivityResult:filename:"+newFile);
                            //上传文件并发送消息
                            uploadFileToServer(newFile);
                        }catch (Exception e){
                            UIUtil.showToast(e.getMessage());
                        }
                    }
                    break;
                case PictureConfig.REQUEST_CAMERA:
                    if(results.size() > 0) {
                        LocalMedia result = results.get(0);
                        //Logger.d("onActivityResult:camera:%s", result.getFileName());
                        try {
                            //拷贝到程序私有目录
                            String newFile = FileUtil.copyGalleryToPrivate(
                                    UIUtil.getContext() ,
                                    Uri.parse(result.getPath()) ,
                                    result.getFileName() ,
                                    result.getHeight() ,
                                    result.getWidth());
                            Logger.d("onActivityResult:camera:filename:"+newFile);
                            //上传文件并发送消息
                            uploadFileToServer(newFile);
                        }catch (Exception e){
                            UIUtil.showToast(e.getMessage());
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    }

    private void showEmotionLayout() {
        mElEmotion.setVisibility(View.VISIBLE);
        mIvEmo.setImageResource(R.mipmap.ic_cheat_keyboard);
    }

    private void hideEmotionLayout() {
        mElEmotion.setVisibility(View.GONE);
        mIvEmo.setImageResource(R.mipmap.ic_cheat_emo);
    }

    private void showMoreLayout() {
        mLlMore.setVisibility(View.VISIBLE);
    }

    private void hideMoreLayout() {
        mLlMore.setVisibility(View.GONE);
    }

    private void closeBottomAndKeyboard() {
        mElEmotion.setVisibility(View.GONE);
        mLlMore.setVisibility(View.GONE);
        if (mEmotionKeyboard != null) {
            mEmotionKeyboard.interceptBackPress();
            mIvEmo.setImageResource(R.mipmap.ic_cheat_emo);
        }
        Logger.d("closeBottomAndKeyboard");
    }

    private void initRefreshLayout() {
        mRefreshLayout.setDelegate(this);
        BGANormalRefreshViewHolder refreshViewHolder = new BGANormalRefreshViewHolder(this, false);
        refreshViewHolder.setRefreshingText("");
        refreshViewHolder.setPullDownRefreshText("");
        refreshViewHolder.setReleaseRefreshText("");
        mRefreshLayout.setRefreshViewHolder(refreshViewHolder);
    }

    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        Logger.d("onBGARefreshLayoutBeginRefreshing");
        getMessage(contact.getUid() , msgPosition , msgLimit);
        //mPresenter.loadMore();
    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        Logger.d("onBGARefreshLayoutBeginLoadingMore");
        return false;
    }

    @Override
    public void onStickerSelected(String categoryName, String stickerName, String stickerBitmapPath) {
    }

    @Override
    public void onEmojiSelected(String key) {
//        LogUtils.e("onEmojiSelected : " + key);
    }

    @Override
    public void onBackPressed() {
        if (mElEmotion.isShown() || mLlMore.isShown()) {
            mEmotionKeyboard.interceptBackPress();
            mIvEmo.setImageResource(R.mipmap.ic_cheat_emo);
        } else {
            super.onBackPressed();
        }
    }

    private void setAdapter() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        mRvMsg.setLayoutManager(layoutManager);
        mAdapter = new SessionAdapter(mMessages , me);
        mRvMsg.setAdapter(mAdapter);
    }

    /**
     * TODO:发送消息请求
     * @param message
     */
    private void sendMessage(UIMessage message){
        Map<String, Object> brocastMap = new HashMap<String, Object>();
        brocastMap.put("type" , BroadcastMsg.DATA_UI_SENDMSG);
        brocastMap.put("mid" , message.getMid());
        brocastMap.put("msg_type" , message.getType());
        brocastMap.put("uid" , message.getUid());
        brocastMap.put("msgtext" , message.getMsgtext());
        BundleUtil bundleUtil = new BundleUtil(BroadcastMsg.SIG_UI_DATA , brocastMap , null);
        BroadcastSender(bundleUtil.getBundle());
        //更新UI的消息列表
        if(message.getType() == UIMessage.MSG_IMG){
            File file = new File(getExternalFilesDir(String.valueOf(me.getUid())) , message.getMsgtext());
            if(file.exists() && file.isFile()){
                DisplayMetrics dm = getResources().getDisplayMetrics();
                int width = dm.widthPixels / 3;     //宽度不超过屏幕1/3
                int height = dm.heightPixels / 2;       //高度不超过屏幕1/2
                message.setBitmap(ImageUtil.getBitmapFromFile(this , file , width , height));
            }
        }
        mMessages.add(message);
        mAdapter.notifyDataSetChanged();
        //滚动到底部
        mRvMsg.scrollToPosition(mMessages.size() - 1);
    }

    /**
     * TODO:上传文件请求
     * @param filename 存放在用户目录uid文件夹下的文件的文件名
     */
    private void uploadFileToServer(String filename){
        Map<String, Object> brocastMap = new HashMap<String, Object>();
        brocastMap.put("type" , BroadcastMsg.DATA_UI_UPLOADPIC);
        brocastMap.put("filename" , filename);
        BundleUtil bundleUtil = new BundleUtil(BroadcastMsg.SIG_UI_DATA , brocastMap , null);
        BroadcastSender(bundleUtil.getBundle());
    }

    /**
     * TODO:获取历史消息
     * @param uid   用户uid
     * @param start 开始序号（倒序）
     * @param limit 获取消息数量
     */
    private void getMessage(int uid , int start , int limit){
        Map<String, Object> brocastMap = new HashMap<String, Object>();
        brocastMap.put("type" , BroadcastMsg.DATA_UI_GETMSG);
        brocastMap.put("uid" , uid);
        brocastMap.put("start" , start);
        brocastMap.put("limit" , limit);
        BundleUtil bundleUtil = new BundleUtil(BroadcastMsg.SIG_UI_DATA , brocastMap , null);
        BroadcastSender(bundleUtil.getBundle());
    }

    /**
     * TODO:将消息列表显示到UI
     * @param messages  消息列表类
     */
    private void loadMessages(List<DBMessage> messages){
        for (DBMessage dbMessage :messages){
            UIMessage uiMessage = new UIMessage();
            uiMessage.setUid(dbMessage.getUid());
            uiMessage.setMid(dbMessage.getMid());
            uiMessage.setIo(dbMessage.getIo());
            uiMessage.setMsgtext(dbMessage.getMsgtext());
            uiMessage.setTimestamp(dbMessage.getTimestamp());
            uiMessage.setStatus(dbMessage.getStatus());
            uiMessage.setType(dbMessage.getType());
            if(dbMessage.getType() == UIMessage.MSG_IMG){
                File file = new File(getExternalFilesDir(String.valueOf(me.getUid())) , dbMessage.getMsgtext());
                if(file.exists() && file.isFile()){
                    DisplayMetrics dm = getResources().getDisplayMetrics();
                    int width = dm.widthPixels / 3;     //宽度不超过屏幕1/3
                    int height = dm.heightPixels / 2;       //高度不超过屏幕1/2
                    uiMessage.setBitmap(ImageUtil.getBitmapFromFile(this , file , width , height));
                }else{
                    /** 通知服务下载图片 */
                    Map<String, Object> brocastMap = new HashMap<String, Object>();
                    brocastMap.put("type" , BroadcastMsg.DATA_UI_DOWNPIC);
                    brocastMap.put("uid" , contact.getUid());
                    brocastMap.put("filename" , dbMessage.getMsgtext());
                    BundleUtil bundleUtil = new BundleUtil(BroadcastMsg.SIG_UI_DATA , brocastMap , null);
                    BroadcastSender(bundleUtil.getBundle());
                }
            }
            mMessages.add(0 , uiMessage);
        }
        msgPosition += messages.size();
        mRefreshLayout.endRefreshing();
        Logger.d("msgPosition:%d" , msgPosition);
        mAdapter.notifyDataSetChanged();
        //滚动到底部
        mRvMsg.scrollToPosition(mMessages.size() - 1);
    }

    /**
     * TODO:重新加载最新20条聊天记录的图片信息
     */
    protected void reloadPic(){
        int i = mMessages.size() >= 20 ? 20 : mMessages.size();
        i --;
        for (; i >= 0 ; i --){
            if (mMessages.get(i).getType() == UIMessage.MSG_IMG && mMessages.get(i).getBitmap() == null){
                File file = new File(getExternalFilesDir(String.valueOf(me.getUid())) , mMessages.get(i).getMsgtext());
                if(file.exists() && file.isFile()){
                    DisplayMetrics dm = getResources().getDisplayMetrics();
                    int width = dm.widthPixels / 3;     //宽度不超过屏幕1/3
                    int height = dm.heightPixels / 2;       //高度不超过屏幕1/2
                    mMessages.get(i).setBitmap(ImageUtil.getBitmapFromFile(this , file , width , height));
                }
            }
        }
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 解决7.0系统拍照崩溃问题
     */
    private void initPhotoError(){
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();
    }
}